<template>
  <div class="customer-detail-container">
    <div class="page-header">
      <el-page-header @back="goBack" :title="'返回客户列表'" :content="'客户详情'" />
    </div>

    <!-- 基本信息卡片 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ curRow.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ curRow.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ handlebirthDateToAge(curRow.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="出生年月">{{ curRow.birthDate || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ curRow.phone }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ curRow.remark || '暂无备注' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 会员卡信息卡片 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>会员卡信息</span>
          <el-button type="primary" size="small" @click="handleAddCard">添加会员卡</el-button>
        </div>
      </template>
      <!-- 会员卡列表 -->
      <div class="card-list">
        <el-empty v-if="memberCards.length === 0" description="暂无会员卡" />
        <el-card v-for="card in memberCards" :key="card.id" class="member-card" shadow="hover">
          <template #header>
            <div class="member-card-header">
              <div class="card-type">
                <el-tag :type="card.cardType === '储值卡' ? 'success' : 'warning'">
                  {{ card.cardType }}
                </el-tag>
                <span class="card-name ml-2">{{ card.cardName }}</span>
              </div>
              <div class="card-actions">
                <el-dropdown trigger="click">
                  <el-button type="primary" size="small">
                    操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleRecharge(card)">
                        <!-- <el-icon><plus /></el-icon> -->
                        {{ card.cardType === '储值卡' ? '充值' : '充次' }}
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleDeduct(card)">
                        <!-- <el-icon><minus /></el-icon> -->
                        {{ card.cardType === '储值卡' ? '扣费' : '扣次' }}
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="handleDeleteCard(card)" class="text-danger">
                        <!-- <el-icon><delete /></el-icon> -->
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="卡内余额" v-if="card.cardType === '储值卡'">
              ￥{{ card.balance || '0.00' }}
            </el-descriptions-item>
            <el-descriptions-item label="剩余次数" v-else>
              {{ card.remainingTimes || 0 }}次
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 交易记录表格 -->
      <div class="transaction-history">
        <div class="table-header">
          <h3>交易记录</h3>
        </div>
        <!-- 交易记录筛选 -->
        <div class="transaction-filter mb-3">
          <el-select v-model="filterCardId" placeholder="选择会员卡" clearable @change="getTransactionRecordsList">
            <el-option label="全部会员卡" value="" />
            <el-option v-for="card in memberCards" :key="card.id" :label="card.cardName" :value="card.id" />
          </el-select>
        </div>
        <el-table :data="transactionRecordsList" style="width: 100%" v-loading="loading">
          <el-table-column prop="createdAt" label="交易时间" width="180" />
          <el-table-column prop="memberCard.cardName" label="会员卡" width="120" />
          <el-table-column prop="type" label="交易类型">
            <template #default="{ row }">
              <el-tag :type="getTransactionTypeTag(row.type)">{{ row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="交易内容">
            <template #default="{ row }">
              <template v-if="row.memberCard.cardType === '储值卡'">
                {{ row.type === '充值' ? '+' : '-' }}￥{{ row.amount }}
              </template>
              <template v-else>
                {{ row.type === '充值' ? '+' : '-' }}{{ row.times }}次
              </template>
            </template>
          </el-table-column>
          <el-table-column label="余额/次数">
            <template #default="{ row }">
              <template v-if="row.memberCard.cardType === '储值卡'">
                ￥{{ row.afterBalance }}
              </template>
              <template v-else>
                {{ row.afterTimes }}次
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-card>

    <!-- 扣卡弹窗 -->
    <el-dialog v-model="deductDialogVisible"
      :title="`${currentCard?.cardName || ''} - ${currentCard?.cardType === '储值卡' ? '扣费' : '扣次'}`" width="30%"
      :close-on-click-modal="false">
      <el-form :model="deductForm" label-width="80px">
        <el-form-item :label="currentCard?.cardType === '储值卡' ? '扣费金额' : '扣除次数'" required>
          <el-input-number v-model="deductForm.value" :min="0" :precision="currentCard?.cardType === '储值卡' ? 2 : 0"
            :step="currentCard?.cardType === '储值卡' ? 100 : 1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="deductForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deductDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitDeduct">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog v-model="rechargeDialogVisible"
      :title="`${currentCard?.cardName || ''} - ${currentCard?.cardType === '储值卡' ? '充值' : '充次'}`" width="30%"
      :close-on-click-modal="false">
      <el-form :model="rechargeForm" label-width="80px">
        <el-form-item :label="currentCard?.cardType === '储值卡' ? '充值金额' : '充值次数'" required>
          <el-input-number v-model="rechargeForm.amount" :min="0" :precision="currentCard?.cardType === '储值卡' ? 2 : 0"
            :step="currentCard?.cardType === '储值卡' ? 100 : 1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="rechargeForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitRecharge">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加会员卡弹窗 -->
    <el-dialog v-model="addCardDialogVisible" title="添加会员卡" width="40%" :close-on-click-modal="false">
      <el-form :model="cardForm" label-width="100px">
        <el-form-item label="卡片类型" required>
          <el-radio-group v-model="cardForm.cardType">
            <el-radio label="储值卡">储值卡</el-radio>
            <el-radio label="次卡">次卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="卡片名称" required>
          <el-input v-model="cardForm.cardName" placeholder="请输入卡片名称" />
        </el-form-item>
        <el-form-item :label="cardForm.cardType === '储值卡' ? '初始金额' : '可用次数'" required>
          <el-input-number v-model="cardForm.balance" :min="0" :precision="cardForm.cardType === '储值卡' ? 2 : 0"
            :step="cardForm.cardType === '储值卡' ? 100 : 1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCardDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitAddCard">
            确定添加
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="customerDetail">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, ArrowDown, Minus, Download, Printer, Edit } from '@element-plus/icons-vue'
import { customerManageApi } from '/@/api/customerManage/index'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
let curRow = ref(JSON.parse(route.query.row))

// 客户基本信息
const customerInfo = ref({
  patientName: '张三',
  gender: '1',
  age: '35',
  phone: '13812345678',
  remark: '定期复诊客户'
})

// 会员卡列表
const memberCards = ref([
  {
    id: '1',
    type: 'balance',
    name: '黄金储值卡',
    balance: 2580.00
  },
  {
    id: '2',
    type: 'times',
    name: '针灸套餐卡',
    remainingTimes: 8,
    totalTimes: 10
  }
])

// 交易记录分页和筛选
const page = ref(1)
const pageSize = ref(10)
const total = ref(25)
const filterCardId = ref('')

// 交易记录列表
const transactionList = ref([
  {
    createTime: '2024-01-20 14:30:00',
    cardId: '1',
    cardName: '黄金储值卡',
    cardType: 'balance',
    type: '充值',
    amount: '1000.00',
    balance: '2580.00',
    remark: '节日优惠充值'
  },
  {
    createTime: '2024-01-15 09:45:00',
    cardId: '2',
    cardName: '针灸套餐卡',
    cardType: 'times',
    type: '使用',
    times: 1,
    remainingTimes: 8,
    remark: '针灸理疗'
  },
  {
    createTime: '2024-01-10 16:20:00',
    cardId: '2',
    cardName: '针灸套餐卡',
    cardType: 'times',
    type: '购买',
    times: 10,
    remainingTimes: 10,
    remark: '针灸套餐卡开卡'
  },
  {
    createTime: '2024-01-05 11:15:00',
    cardId: '1',
    cardName: '黄金储值卡',
    cardType: 'balance',
    type: '消费',
    amount: '420.00',
    balance: '160.00',
    remark: '中医诊疗'
  }
])

const handlebirthDateToAge = (birthDate) => {
  if (!birthDate) return '保密';

  const today = new Date();
  const birth = new Date(birthDate);

  // 计算年份差
  let age = today.getFullYear() - birth.getFullYear();

  // 检查是否已过生日
  const monthDiff = today.getMonth() - birth.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }

  return age;
}


const transactionRecordsList = ref([]) // 交易记录列表
// 根据筛选条件获取交易记录
// const filteredTransactionList = computed(() => {
//   if (!filterCardId.value) return transactionList.value
//   return transactionList.value.filter(item => item.cardId === filterCardId.value)
// })

// 获取交易类型对应的标签类型
const getTransactionTypeTag = (type: string) => {
  switch (type) {
    case '充值':
    case '购买':
      return 'success'
    case '消费':
    case '使用':
      return 'warning'
    default:
      return 'info'
  }
}

// 充值相关
const rechargeDialogVisible = ref(false)
const currentCard = ref<any>(null)
const rechargeForm = reactive({
  amount: 0,
  remark: ''
})

// 添加会员卡相关
const addCardDialogVisible = ref(false)
const cardForm = reactive({
  cardType: '储值卡',
  cardName: '',
  balance: 0,
  remainingTimes: 1,
  remark: ''
})

// 获取客户详情
const getCustomerDetail = async () => {
  // 模拟异步加载效果
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 扣卡相关
const deductDialogVisible = ref(false)
const deductForm = reactive({
  value: 0,
  remark: ''
})

// 处理扣卡
const handleDeduct = (card: any) => {
  currentCard.value = card
  deductForm.value = 0
  deductForm.remark = ''
  deductDialogVisible.value = true
}

// 提交扣卡
const submitDeduct = async () => {
  console.log(deductForm);

  if (deductForm.value <= 0) {
    ElMessage.warning(`请输入有效的${currentCard.value.cardType === '储值卡' ? '金额' : '次数'}`)
    return
  }


  // 验证余额/次数是否足够
  if (currentCard.value.cardType === '储值卡' && currentCard.value.balance < deductForm.value) {
    ElMessage.warning('卡内余额不足')
    return
  } else if (currentCard.value.cardType === '次卡' && currentCard.value.cardType.remainingTimes < deductForm.value) {
    ElMessage.warning('剩余次数不足')
    return
  }

  let obj = null
  if (currentCard.value.cardType == "储值卡") {
    obj = {
      cardId: currentCard.value.id,
      amount: deductForm.value,
      remark: deductForm.remark
    }
  } else {
    obj = {
      cardId: currentCard.value.id,
      times: deductForm.value,
      remark: deductForm.remark
    }
  }
  if (deductForm.value <= 0) {
    ElMessage.warning(`请输入有效的${currentCard.value.cardType === '储值卡' ? '金额' : '次数'}`)
    return
  }
  submitting.value = true
  customerManageApi().consumption(obj).then(res => {
    ElMessage.success('消费成功')
    deductDialogVisible.value = false
    getCustomerCardsList()
    submitting.value = false
  })
}

// 处理充值
const handleRecharge = (card: any) => {
  currentCard.value = card
  rechargeForm.amount = 0
  rechargeForm.remark = ''
  rechargeDialogVisible.value = true
}

// 提交充值
const submitRecharge = async () => {
  console.log(rechargeForm)
  let obj = null
  if (currentCard.value.cardType == "储值卡") {
    obj = {
      cardId: currentCard.value.id,
      amount: rechargeForm.amount,
      remark: rechargeForm.remark
    }
  } else {
    obj = {
      cardId: currentCard.value.id,
      times: rechargeForm.amount,
      remark: rechargeForm.remark
    }
  }
  if (rechargeForm.amount <= 0) {
    ElMessage.warning(`请输入有效的${currentCard.value.type === 'balance' ? '金额' : '次数'}`)
    return
  }
  submitting.value = true
  customerManageApi().recharge(obj).then(res => {
    ElMessage.success('消费成功')
    rechargeDialogVisible.value = false
    getCustomerCardsList()
    submitting.value = false
  })
}

// 处理删除会员卡
const handleDeleteCard = (card: any) => {

  ElMessageBox.confirm(`确定要删除会员卡"${card.cardName}"吗？此操作不可恢复。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
      let obj = {
        id: card.id,
      }

      submitting.value = true
      customerManageApi().deleteCard(obj).then(res => {
        ElMessage.success('会员卡删除成功')
        getCustomerCardsList()
        submitting.value = false
      })
  })
}

// 处理添加会员卡
const handleAddCard = () => {
  cardForm.cardType = '储值卡'
  cardForm.cardName = ''
  cardForm.balance = 0
  cardForm.remainingTimes = 0
  cardForm.remark = ''
  addCardDialogVisible.value = true
}

// 提交添加会员卡
const submitAddCard = async () => {
  if (!cardForm.cardName) {
    ElMessage.warning('请输入卡片名称')
    return
  }
  // if (cardForm.initialValue <= 0) {
  //   ElMessage.warning(`请输入有效的${cardForm.type === 'balance' ? '金额' : '次数'}`)
  //   return
  // }

  try {
    submitting.value = true
    if (cardForm.cardType == '次卡') {
      cardForm.remainingTimes = cardForm.balance
      cardForm.balance = 0
    } else {
      cardForm.remainingTimes = 0
    }
    let obj = Object.assign({
      customerId: curRow.value.id,
    }, cardForm)
    customerManageApi().createCustomerCards(obj).then(res => {
      ElMessage.success('添加会员卡成功')
      addCardDialogVisible.value = false
      getCustomerCardsList()
    })
  } catch (error) {
    ElMessage.error('添加会员卡失败')
  } finally {
    submitting.value = false
  }
}

// 获取交易记录
const getTransactionRecordsList = async () => {
  if (memberCards.value.length == 0) {
    return
  }
  let obj = {
    // customerId: curRow.value.id,
    page: page.value,
    pageSize: pageSize.value,
    cardId: filterCardId.value // 卡片ID
  }
  console.log(obj, 'akwjhdnjh');

  customerManageApi().getTransactionRecords(obj).then(res => {
    transactionRecordsList.value = res.data.list
    total.value = res.data.total
  })
}
// getTransactionRecordsList()

// 获取会员卡信息
const getCustomerCardsList = async () => {
  let obj = {
    customerId: curRow.value.id,
  }
  customerManageApi().getCustomerCards(obj).then(res => {
    memberCards.value = res.data
    getTransactionRecordsList()
  })
}
getCustomerCardsList()

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTransactionRecordsList()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  getTransactionRecordsList()
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  getCustomerDetail()
})
</script>

<style scoped lang="scss">
.customer-detail-container {
  .card-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .member-card {
    .member-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-type {
        display: flex;
        align-items: center;

        .card-name {
          margin-left: 8px;
          font-weight: bold;
        }
      }
    }
  }

  .transaction-filter {
    margin-bottom: 15px;
  }

  padding: 20px;

  .page-header {
    margin-bottom: 20px;
  }

  .detail-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .transaction-history {
    margin-top: 20px;

    .table-header {
      margin-bottom: 15px;

      h3 {
        margin: 0;
        color: #303133;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
